package com.alvin.mbp.action;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.alvin.mbp.entity.PointMember;
import com.alvin.mbp.service.PointMemberService;
import com.alvin.mbp.util.EncryptUtils;

@Controller
public class UserAction {

	@Autowired
	private PointMemberService pointMemberService;

	@RequestMapping(value = "/user/changePwd.htm", method = RequestMethod.GET)
	public String changePwd() {
		return "/user/password";
	}

	@RequestMapping(value = "/user/info.htm", method = RequestMethod.GET)
	public String info() {
		return "/user/info";
	}

	@RequestMapping(value = "/user/changePwd.htm", method = RequestMethod.POST)
	public String changePwd(Model model, HttpServletRequest request, String oldPwd, String password, String password2) {
		PointMember member = (PointMember) request.getSession().getAttribute("MEMBER");
		member = pointMemberService.findById(member.getId());
		if (member.getPassword().equals(EncryptUtils.md5(oldPwd)) && password.equals(password2)) {
			member = pointMemberService.changePwd(member.getId(), EncryptUtils.md5(password));
			return "redirect:/home.htm";
		} else {
			return "/user/password";
		}
	}

	@RequestMapping(value = "/user/info.htm", method = RequestMethod.POST)
	public String info(Model model, HttpServletRequest request, PointMember member) {
		String msg = "";
		try {
			pointMemberService.update(member);
			msg = "个人信息修改成功！";
			// 更新SESSION中的用户信息
			request.getSession().setAttribute("MEMBER", pointMemberService.findById(member.getId()));
		} catch (Exception e) {
			msg = "系统繁忙，请稍后再试！";
		}
		model.addAttribute("msg", msg);
		return "/user/info";
	}

}
